package com.yex.service.otc.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yex.base.ZeroResultException;
import com.yex.constant.Constant;
import com.yex.dao.otc.OtcAppealDao;
import com.yex.dao.otc.OtcCoinDao;
import com.yex.dao.otc.OtcEntrustDao;
import com.yex.dao.otc.OtcVoucherDao;
import com.yex.utils.JsonResultVo;
import com.yex.entity.otc.*;
import com.yex.entity.UserEntity;
import com.yex.service.UserService;
import com.yex.service.otc.IOtcAppealService;
import com.yex.service.otc.IOtcOrderService;
import com.yex.utils.vo.OtcAppealOperEnum;
import com.yex.utils.vo.OtcAppealVo;
import com.yex.utils.vo.OtcOperEnum;
import com.yex.utils.vo.RespInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * otc 订单表 服务实现类
 * </p>
 *
 * @author Little Liu
 * @since 2018-05-12
 */
@Service
public class OtcAppealServiceImpl extends ServiceImpl<OtcAppealDao, OtcAppeal> implements IOtcAppealService {

	@Autowired
	private OtcVoucherDao otcVoucherMapper;
	
	@Autowired
	private IOtcOrderService otcOrderService;
	
	@Autowired
    private OtcCoinDao otcCoinMapper;
	
	@Autowired
	private OtcEntrustDao otcEntrustMapper;
	
	@Autowired
	private UserService fuserMapper;
	
	@Override
	@Transactional
	public JsonResultVo updateOtcAppeal(OtcAppealVo otcAppealVo) {
		
		Date nowDate = new Date();
		OtcOrder otcOrder = otcOrderService.selectById(otcAppealVo.getOrderId()); //根据订单id查询订单
		OtcAppeal otcAppeal = baseMapper.getOtcAppealByOrderId(otcAppealVo.getOrderId());
		OtcEntrust otcEntrust = otcEntrustMapper.selectById(otcOrder.getEntrustId());  //根据委托id查询，委托信息
		Integer buyerUserId = null;
		Integer sellerUserId = null;
		if(otcEntrust.getType()==0) {
			buyerUserId = otcEntrust.getUserId();
			sellerUserId = otcOrder.getUserId();
		}else {
			buyerUserId = otcOrder.getUserId();
			sellerUserId = otcEntrust.getUserId();
		}
		//上传凭证
		if(otcAppealVo.getOtcAppealOperEnum()==OtcAppealOperEnum.UPLOAD_VOCHER) {
			
			if(otcAppeal.getUpVoucherStatus()!=1) {
				return new JsonResultVo(false, "已上传凭证", -1);
			}
			
			otcAppeal.setUpVoucherStatus(2);
			otcAppeal.setUpVoucherDate(nowDate);
			otcAppeal.setOldStatus(1);
			int result = baseMapper.updateUpVoucher(otcAppeal);
		
			if(otcAppealVo.getImgUrls()==null || otcAppealVo.getImgUrls().length==0) {
				throw new ZeroResultException(new JsonResultVo(false, "请至少上传一张凭证", -1) );
			}
			if(result<=0) {
				throw new ZeroResultException(new JsonResultVo(false, "数据异常", -1) );
			}
			for(String imgUrl : otcAppealVo.getImgUrls()) {
				OtcVoucher otcVoucher = new OtcVoucher();
		        otcVoucher.setOrderId(otcAppealVo.getOrderId());
		        otcVoucher.setUserId(otcAppealVo.getUserId());
				String domain = Constant.Domain;
				if ("true".equals(Constant.IS_OPEN_OSS)) {
					domain = Constant.OSSURL;
				}
		        otcVoucher.setImg(imgUrl.replace(domain,""));
		        otcVoucher.setCreateTime(nowDate);
		      
		        result = otcVoucherMapper.insert(otcVoucher);
		        if(result<=0) {
					throw new ZeroResultException(new JsonResultVo(false, "数据异常", -1) );
				}
			}
			
			
			//给卖家发送短信
	        UserEntity fuser = null;
	        String content = "";
	        if(otcEntrust.getType()==0) {
	        	fuser = fuserMapper.selectById(otcOrder.getUserId());  
	        	
	        }else {
	        	fuser = fuserMapper.selectById(otcEntrust.getUserId());  
	        	
	        }
//	        content= (String)redisService.getConfig("buyer_upload_voucher") ;
//	        OtcCoin otcCoin=otcCoinMapper.selectById(otcEntrust.getCoinId());//货币信息
//      	    content = content.replace("{coin_type}", otcCoin.getCoinName())
//      	              .replace("{trading_time}", Utils.dateFormat(new Timestamp((new Date()).getTime())))
//      	              .replace("{price}", MathUtil.getBigDecimalString(otcOrder.getPrize(),2))
//      	              .replace("{total_price}", MathUtil.getBigDecimalString(otcOrder.getAmount(),2))
//      	            .replace("{num}", MathUtil.getBigDecimalString(otcOrder.getCountNum(),4))
//      	              .replace("{order_number}", otcOrder.getOrderNumber());//真正的短信内容
//  	        boolean flag =  userSupport.SendOtcMessage(fuser, content, 0); //发送短信通知
//  	        if(!flag) {
//  	        	new ZeroResultException(new JsonResultVo(true, "服务异常", -3));
//  	        }
			
			
	    	
	        
	        return new JsonResultVo(true, "上传凭证成功", 0);
		}else if(otcAppealVo.getOtcAppealOperEnum()==OtcAppealOperEnum.APPLY_APPEAL) {
			
			if(otcAppeal.getArbitrationStatus()!=0) {
				return new JsonResultVo(false, "已申请仲裁，请耐心等待", -1);
			}
			
			//申请仲裁
			otcAppeal.setArbitrationStatus(1);
			otcAppeal.setApplyArbitrationDate(nowDate);
			otcAppeal.setOldStatus(0);
			int result = baseMapper.updateApplyArbitration(otcAppeal);
			if(result<=0) {
				throw new ZeroResultException(new JsonResultVo(true, "状态改变", -1) );
			}
			//给买家发短信
		    UserEntity fuser = null;
	        String content = "";
	        if(otcEntrust.getType()==0) {
	        	fuser = fuserMapper.selectById(otcEntrust.getUserId());  
	        	
	        }else {
	        	fuser = fuserMapper.selectById(otcOrder.getUserId());  
	        	
	        }
//	        content= (String)redisService.getConfig("buyer_arbitration") ;
//	        OtcCoin otcCoin=otcCoinMapper.selectById(otcEntrust.getCoinId());//货币信息
//      	    content = content.replace("{coin_type}", otcCoin.getCoinName())
//      	              .replace("{trading_time}", Utils.dateFormat(new Timestamp((new Date()).getTime())))
//      	              .replace("{price}", MathUtil.getBigDecimalString(otcOrder.getPrize(),2))
//      	              .replace("{total_price}", MathUtil.getBigDecimalString(otcOrder.getAmount(),2))
//      	              .replace("{num}", MathUtil.getBigDecimalString(otcOrder.getCountNum(),4))
//      	            .replace("{order_number}", otcOrder.getOrderNumber());//真正的短信内容
//  	        boolean flag =  userSupport.SendOtcMessage(fuser, content, 0); //发送短信通知
//  	        if(!flag) {
//  	        	new ZeroResultException(new JsonResultVo(false, "服务异常", -3));
//  	        }
			
		}else if(otcAppealVo.getOtcAppealOperEnum()==OtcAppealOperEnum.APPLY_APPEAL_ADMIN) {

			if(otcAppeal.getArbitrationStatus()!=0) {
				return new JsonResultVo(false, "已申请仲裁，请耐心等待", -1);
			}

			//申请仲裁
			otcAppeal.setArbitrationStatus(1);
			otcAppeal.setApplyArbitrationDate(nowDate);
			otcAppeal.setOldStatus(0);
			otcAppeal.setServersId(otcAppealVo.getAdminId());
			int result = baseMapper.updateApplyArbitrationAdmin(otcAppeal);
			if(result<=0) {
				throw new ZeroResultException(new JsonResultVo(true, "状态改变", -1) );
			}
			//给买家发短信
			UserEntity fuser = null;
			String content = "";
			if(otcEntrust.getType()==0) {
				fuser = fuserMapper.selectById(otcEntrust.getUserId());

			}else {
				fuser = fuserMapper.selectById(otcOrder.getUserId());

			}
//			content= (String)redisService.getConfig("buyer_arbitration") ;
//			OtcCoin otcCoin=otcCoinMapper.selectById(otcEntrust.getCoinId());//货币信息
//			content = content.replace("{coin_type}", otcCoin.getCoinName())
//					.replace("{trading_time}", Utils.dateFormat(new Timestamp((new Date()).getTime())))
//					.replace("{price}", MathUtil.getBigDecimalString(otcOrder.getPrize(),2))
//					.replace("{total_price}", MathUtil.getBigDecimalString(otcOrder.getAmount(),2))
//					.replace("{num}", MathUtil.getBigDecimalString(otcOrder.getCountNum(),4))
//					.replace("{order_number}", otcOrder.getOrderNumber());//真正的短信内容
//			boolean flag =  userSupport.SendOtcMessage(fuser, content, 0); //发送短信通知
//			if(!flag) {
//				new ZeroResultException(new JsonResultVo(false, "服务异常", -3));
//			}

		}else if(otcAppealVo.getOtcAppealOperEnum()==OtcAppealOperEnum.SELLER_CANCEL) {
			//买家取消
			
			if(otcAppeal==null) {
				throw new ZeroResultException(new JsonResultVo(RespInfo.FAILURE.getMsg()));
			}
			if(otcAppeal.getArbitrationStatus()!=0 && otcAppeal.getArbitrationStatus()!=1) {
				return new JsonResultVo(false, "状态已改变，请勿重复操作", -1);
			}
			otcAppeal.setArbitrationStatus(2);
			otcAppeal.setArbitrationDate(nowDate);
			otcAppeal.setOldStatus(0);
			int result = baseMapper.updateDealArbitration(otcAppeal);
			if(result<=0) {
				throw new ZeroResultException(new JsonResultVo(RespInfo.FAILURE.getMsg()));
			}
			
		}else if(otcAppealVo.getOtcAppealOperEnum()==OtcAppealOperEnum.BUYER_WIN) {
			//买方胜诉
			if(otcAppeal.getArbitrationStatus()!=1) {
				return new JsonResultVo(false, "未申请仲裁，请勿操作", -1);
			}
			otcAppeal.setArbitrationId(otcAppealVo.getAdminId());
			otcAppeal.setArbitrationStatus(3);
			otcAppeal.setArbitrationDate(nowDate);
			otcAppeal.setOldStatus(1);
			int result = baseMapper.updateDealArbitration(otcAppeal);
			if(result<=0) {
				throw new ZeroResultException(new JsonResultVo(false, "数据异常", -1) );
			}
			
			//放币
			JsonResultVo resultVo = otcOrderService.updateOrder(otcAppealVo.getOrderId(), OtcOperEnum.COMFIRM_MONEY, sellerUserId,null,true);
			if(!resultVo.isSuccess()) {
				throw new ZeroResultException(resultVo);
			}
			return resultVo;
		}else if(otcAppealVo.getOtcAppealOperEnum()==OtcAppealOperEnum.SELLER_WIN) {
			if(otcAppeal.getArbitrationStatus()!=1) {
				return new JsonResultVo(false, "未申请仲裁，请勿操作", -1);
			}
			//卖方胜诉
			otcAppeal.setArbitrationId(otcAppealVo.getAdminId());
			otcAppeal.setArbitrationStatus(4);
			otcAppeal.setArbitrationDate(nowDate);
			otcAppeal.setOldStatus(1);
			int result = baseMapper.updateDealArbitration(otcAppeal);
			if(result<=0) {
				throw new ZeroResultException(new JsonResultVo(false, "处理状态已改变", -1) );
			}
			JsonResultVo resultVo = otcOrderService.updateOrder(otcAppealVo.getOrderId(), OtcOperEnum.SERVICE_CANCEL, buyerUserId,null,true);
			if(!resultVo.isSuccess()) {
				throw new ZeroResultException(resultVo);
			}
			return resultVo;
		}else if(otcAppealVo.getOtcAppealOperEnum()==OtcAppealOperEnum.SERVICE_DEAL) {
			if(otcAppeal.getServersStatus()!=1) {
				return new JsonResultVo(false, "请勿重复处理", -1);
			}
			//处理客诉
			otcAppeal.setServersId(otcAppealVo.getAdminId());
			otcAppeal.setServersDate(nowDate);
			otcAppeal.setServersStatus(2);
			otcAppeal.setOldStatus(1);
			int result = baseMapper.updateDealServers(otcAppeal);
			if(result<=0) {
				throw new ZeroResultException(new JsonResultVo(false, "已处理，请勿重复处理", -1) );
			}
		
			return new JsonResultVo(true, "客诉处理成功", 0);
		}
	
		return new JsonResultVo(true, "操作成功", 0);
	}
	

}
